package com.yu.mall.interceptor;

import com.alibaba.fastjson.JSON;
import com.yu.mall.constants.UserConstants;
import com.yu.mall.entity.AdminUser;
import com.yu.mall.exception.ServiceException;
import com.yu.mall.util.PasswordUtil;
import com.yu.mall.util.RedisUtil;
import com.yu.mall.util.ResponseUtils;
import com.yu.mall.util.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AppLoginInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		UserConstants.USER_LOCAL.remove();
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object object) throws Exception {
		String method = request.getMethod();
		if("OPTIONS".equals(method) || "options".equals(method)){
			return true;
		}
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			return ResponseUtils.writeJson(response, ResultUtils.error("-1","登录超时"));
		}
		String openid = request.getHeader("openid");
		String key = PasswordUtil.decode3Des(PasswordUtil.KEY, token);
		String userInfo = (String)redisUtil.get(key);
		if(StringUtils.isEmpty(userInfo)){
			return ResponseUtils.writeJson(response, ResultUtils.error("-1","登录超时"));
		}
		if(StringUtils.isEmpty(openid)){
			AdminUser adminUser = JSON.parseObject(userInfo, AdminUser.class);
			UserConstants.USER_LOCAL.set(adminUser);
		}
		return true;
	}

}
